<template>
  <el-dialog v-model="isShowResetDialog" title='重置密码' width="600" :before-close="closeResetDialog">
    <!-- 校验规则为rules，直接定义所有参数的rules，但是<el-form-item>中的prop还是要设置，且还需要新增一个interface -->
    <el-form ref="resetFormRef" :model="resetForm">
      <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName" :rules="[
        { required: true, message: '用户名不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="resetForm.userName" placeholder="请输入用户名"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeResetDialog()">取消</el-button>
        <el-button type="primary" @click="submitResetForm(resetFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="isShowVerifyDialog" :title="verifyForm.userName ? '修改密码':'设置密码'" width="600" :before-close="closeVerifyDialog">

    <el-form ref="verifyFormRef" :model="verifyForm" :rules="passwordRules">
      <el-form-item v-if="!verifyForm.userName">
        <el-text class="mx-1" type="danger" size="large" style="display: flex;text-align: center;">
        一条包含验证码的信息已发送至你的邮箱：{{ email }} 
        </el-text>
        <el-text class="mx-1" type="danger" size="large">请输入验证码以继续</el-text>
      </el-form-item>
      <el-form-item v-if="!verifyForm.userName" label="验证码" :label-width="formLabelWidth" prop="verifyCode" :rules="[
        { required: true, message: '验证码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="verifyForm.verifyCode" placeholder="请输入验证码"/>
      </el-form-item>
      <el-form-item v-if="verifyForm.userName" label="原密码" :label-width="formLabelWidth" prop="oldPassword" :rules="[
        { required: true, message: '原密码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="verifyForm.oldPassword" show-password placeholder="请输入包含英文字母大小写、数字和特殊符号的 6-20 位组合"/>
      </el-form-item>
      <el-form-item label="新密码" :label-width="formLabelWidth" prop="password" :rules="[
        { required: true, message: '新密码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="verifyForm.password" show-password placeholder="请输入包含英文字母大小写、数字和特殊符号的 6-20 位组合"/>
      </el-form-item>
      <el-form-item label="确认密码" :label-width="formLabelWidth" prop="passwordbak" :rules="[
        { required: true, message: '确认密码不能为空', trigger: 'blur' }
      ]">
        <el-input v-model="verifyForm.passwordbak" show-password placeholder="请再次输入密码"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeVerifyDialog()">取消</el-button>
        <el-button type="primary" @click="submitVerifyForm(verifyFormRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive,ref } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElLoading } from 'element-plus';
import { post } from '~/composables/utils';

const isShowResetDialog = ref(false);
const isShowVerifyDialog = ref(false);
const resetFormRef = ref<FormInstance>();
const verifyFormRef = ref<FormInstance>();
// 弹框里面label的宽度
const formLabelWidth = '80px';
const email = ref();
const resetForm = reactive({
  userName: ''
});
const verifyForm = reactive({
  userName: '',
  verifyCode: '',
  oldPassword: '',
  password: '',
  passwordbak:''
});

// 校验密码
const validatePass = (rule: any, value: any, callback: any) => {
  const passReg = /^[^\s\u4e00-\u9fa5]{6,20}$/;
  if (!passReg.test(value)) {
    callback(new Error('请输入包含英文字母大小写、数字和特殊符号的 6-20 位组合'))
  } else {
    if (verifyForm.password !== '') {
      if (!verifyFormRef.value) return
      verifyFormRef.value.validateField('password')
    }
    callback()
  }
}
// 校验重复密码
const validatePassbak = (rule: any, value: any, callback: any) => {
 if (value !== verifyForm.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

const passwordRules = reactive<FormRules<typeof verifyForm>>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  passwordbak: [{ validator: validatePassbak, trigger: 'blur' }],
})
function closeResetDialog() {
  isShowResetDialog.value = false;
  clearResetForm();
}
// 重置数据
const clearResetForm = () => {
  resetForm.userName = '';
}

function closeVerifyDialog() {
  isShowVerifyDialog.value = false;
  clearVerifyForm();
}
// 重置数据
const clearVerifyForm = () => {
  verifyForm.userName = '';
  verifyForm.password = '';
  verifyForm.passwordbak = '';
  verifyForm.verifyCode = '';
  verifyForm.oldPassword = '';
}

const submitResetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      getVerifyCode();
    } else {
      console.log('error submit!')
    }
  })
};

// 重置密码获取验证码
const getVerifyCode = async () => {
  const response = await post('/user/getVerifyCode', { 'userName': resetForm.userName});
  if (response.code != 200){
    ElMessage.error(response.msg);
  } else {
    email.value = response.data;
  }
  verifyForm.userName = resetForm.userName;
  closeResetDialog();
  isShowVerifyDialog.value = true;
};

// 重置密码修改密码
const submitVerifyForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      resetPassword();
    } else {
      console.log('error submit!')
    }
  })
};

const resetPassword = async () => {
  const response = await post('/user/resetPassword', verifyForm);
  if (response.code != 200){
    ElMessage.error(response.msg);
  } else {
    ElMessage.success('修改成功');
    closeVerifyDialog();
  }
};

// 从登录页面的忘记密码进入没有data，从登录后的修改密码进入有data，就是userName
const init = (data?: any) => {
  if (data) {
    // 登录后的修改密码进来，直接显示修改密码的弹框
    isShowVerifyDialog.value = true;
    Object.assign(verifyForm, data);
  } else {
    // 登录页面的忘记密码进来，要先显示输入用户名的弹框
    isShowResetDialog.value = true;
  }
};
defineExpose({ init });
</script>
<style lang="scss" scoped>
/* 为了页面刷新不出现滚动条 */
.ep-scrollbar {
  height: auto;
}
.ep-form-item__content {
  display: grid;
}
</style>